<?php

declare (strict_types=1);

namespace app\checkin\controller;

use think\admin\helper\QueryHelper;

/**
 * 门禁设备管理
 * @class Device
 * @package app\checkin\controller
 */
class Device extends Base
{
    /**
     * 数据表名
     * @var string
     */
    protected $table = 'checkin_device';
    /**
     * 门禁设备管理
     * @auth true
     * @menu true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        $this->title = '门禁设备管理';
        \app\checkin\model\Device::mQuery()->layTable(function () {
            // 传递门店选项到视图
            $this->assign('stores', $this->getStoreOptions());
        }, function (QueryHelper $query) {
            $query->like('sn,name')->equal('status,store_id');
            $query->dateBetween('create_time');

            // 预加载门店名称
            $query->with(['store' => static function ($q) {
                $q->field('id,name');
            }]);

            // 如果不是超级管理员，只显示自己门店的设备
            if (!$this->isMaster) {
                $query->where(['store_id' => $this->storeId]);
            }
        });
    }

    /**
     * 添加门禁设备
     * @auth true
     */
    public function add()
    {
        $this->title = '添加门禁设备';
        $this->_applyFormToken();
        \app\checkin\model\Device::mForm('device/form');
    }

    /**
     * 编辑门禁设备
     * @auth true
     */
    public function edit()
    {
        $this->title = '编辑门禁设备';
        $this->_applyFormToken();
        \app\checkin\model\Device::mForm('device/form');
    }

    /**
     * 表单数据处理
     * @param array $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function _form_filter(array &$data)
    {
        if ($this->request->isPost()) {
            // 验证设备序列号唯一性
            if (!empty($data['sn'])) {
                $map = ['sn' => $data['sn']];
                if (!empty($data['id'])) $map[] = ['id', '<>', $data['id']];
                if (\app\checkin\model\Device::mk()->where($map)->count() > 0) {
                    $this->error('设备序列号已经存在！');
                }
            }

            // 自动生成设备密码
            if (empty($data['passwd']) && !empty($data['sn'])) {
                $data['passwd'] = md5($data['sn'] . time());
            }

            // 设置默认值
            $data['create_time'] = $data['create_time'] ?? date('Y-m-d H:i:s');
            $data['update_time'] = date('Y-m-d H:i:s');
        } else {
            // GET请求时传递门店选项
            $this->assign('stores', $this->getStoreOptions());
        }
    }

    /**
     * 修改设备状态
     * @auth true
     */
    public function state()
    {
        \app\checkin\model\Device::mSave($this->_vali([
            'status.in:0,1'  => '状态值范围异常！',
        ]));
    }

    /**
     * 删除门禁设备
     * @auth true
     */
    public function remove()
    {
        \app\checkin\model\Device::mDelete();
    }

    /**
     * 重置设备密码
     * @auth true
     */
    public function resetPassword()
    {
        $data = $this->_vali(['id.require' => '设备ID不能为空！']);
        try {
            $device = \app\checkin\model\Device::mk()->where(['id' => $data['id']])->findOrEmpty();
            if ($device->isEmpty()) $this->error('设备不存在！');

            $newPassword = md5($device->getAttr('sn') . time());
            $device->save([
                'passwd' => $newPassword,
                'update_time' => date('Y-m-d H:i:s')
            ]);

            $this->success('密码重置成功！新密码：' . $newPassword);
        } catch (\Exception $e) {
            $this->error('密码重置失败：' . $e->getMessage());
        }
    }

    /**
     * 设备在线状态统计
     * @auth true
     * @menu true
     */
    public function statistics()
    {
        $this->title = '设备统计';

        // 统计数据
        $query = \app\checkin\model\Device::mk();

        // 如果不是超级管理员，只统计自己门店的设备
        if (!$this->isMaster) {
            $query = $query->where(['store_id' => $this->storeId]);
        }

        $total = $query->count();
        $online = $query->where(['online_status' => 1])->count();
        $offline = $total - $online;
        $enabled = $query->where(['status' => 1])->count();
        $disabled = $total - $enabled;

        $this->assign('statistics', [
            'total' => $total,
            'online' => $online,
            'offline' => $offline,
            'enabled' => $enabled,
            'disabled' => $disabled
        ]);

        $this->fetch();
    }

    /**
     * 获取门店列表（用于下拉选择）
     */
    protected function getStoreOptions()
    {
        // 从数据库读取启用的门店，非超管仅返回自身门店
        $map = ['status' => 1];
        if (!$this->isMaster && !empty($this->storeId)) {
            $map['id'] = $this->storeId;
        }
        try {
            return \app\checkin\model\Store::mk()
                ->where($map)
                ->order('sort desc,id desc')
                ->column('name', 'id');
        } catch (\Throwable $e) {
            // 查询异常时返回空数组以保证表单可渲染
            return [];
        }
    }
}
